package com.example.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.dao.DemoDao;
import com.example.demo.entity.DemoEntity;
import com.example.demo.service.DemoService;
import com.example.demo.utils.MinimumEditDistance;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author artboy
 */
@Service
public class DemoServiceImpl extends ServiceImpl<DemoDao, DemoEntity> implements DemoService {

    @Override
    public List<DemoEntity> matchUserByTags(List<String> tags) {
        List<DemoEntity> demoEntities = baseMapper.selectList(null);
        Gson gson = new Gson();
        // <用户列表下标, 相似度>
        HashMap<Integer, Integer> indexDistanceMap = new HashMap<>();
        for (int i = 0; i < demoEntities.size(); i ++) {
            DemoEntity demoEntity = demoEntities.get(i);
            String tags1 = demoEntity.getTags();
            // 无标签
            if (StringUtils.isEmpty(tags1)) {
                continue;
            }
            List<String> userTag = gson.fromJson(tags1, new TypeToken<List<String>>() {
            }.getType());
            Integer score = MinimumEditDistance.minimumEditDistance(tags, userTag);
            indexDistanceMap.put(i, score);
        }
        // 对相似度进行升序排序
        //利用Map的entrySet方法，转化为list进行排序
        List<Map.Entry<Integer, Integer>> entryList = new ArrayList<>(indexDistanceMap.entrySet());
        //利用Collections的sort方法对list排序
        entryList.sort(Comparator.comparingInt(Map.Entry::getValue));
        List<DemoEntity> collect = entryList.stream().limit(5).map(
                entry -> demoEntities.get(entry.getKey())
        ).collect(Collectors.toList());
        return collect;
    }
}
